package com.yiding.sys.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiding.sys.common.utils.HashUtil;
import com.yiding.sys.dao.SysUserMapper;
import com.yiding.sys.pojo.SysUser;
import com.yiding.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/8/7
 * Description: No Description
 */

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Override
	public Boolean login(String username, String password) {
		try {
			// 身份验证
			Subject currentUser = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// 登录
			currentUser.login(token);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Boolean addUser(SysUser user) {
		// 判断用户名是否被占用
		if (this.getUserByUsername(user.getUsername()) != null)
			return false;

		Map<String, String> map = HashUtil.generatePassword(user.getUsername(), user.getPassword());
		user.setPassword(MapUtil.getStr(map, "hash"));
		user.setSalt(MapUtil.getStr(map, "salt"));

		Integer result = sysUserMapper.insert(user);

		return result > 0;
	}

	@Override
	public SysUser getUserByUsername(String username) {
		return sysUserMapper.selectUserByUsername(username);
	}

}
